package cn.edu.jxau.core.process.spectrumutil;

import cn.edu.jaxu.bluedot.AlgorithmInterface.AnalysisAlgorithm;
import cn.edu.jaxu.bluedot.AlgorithmInterface.PretreatmentAlgorithm;
import cn.edu.jaxu.bluedot.AlgorithmInterface.exception.PretreatmentAlgorithmException;
import cn.edu.jxau.core.util.upload.FileUpload;
import cn.edu.jxau.core.vo.SpectrumFile;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.net.URLClassLoader;

/**
 * 算法服务
 * <p>
 * MangoDai
 * 2017 08 29 7:45 PM
 */
public class AlgorithmUtils {
    private static Logger logger = LoggerFactory.getLogger(AlgorithmUtils.class);
    private static final String PRETREATMENTALGORITHMIMPL = "cn.edu.jaxu.bluedot.AlgorithmImpl";

    /**
     * 使用Jar包来预处理光谱对象
     * 地址会自动拼装成绝对路径
     * @param algorithmRealPath   算法对象的地址
     * @param spectrumfile        光谱对象
     * @param isAnalysisAlgorithm 是分析算法吗
     * @throws ClassNotFoundException 类没有找到
     * @throws InstantiationException 类实例化失败
     * @throws IllegalAccessException 实例化没有权限
     * @throws IOException            Io读写失败
     */
    public static JSONArray useJar2PrementSpectrum(String algorithmRealPath, SpectrumFile spectrumfile, boolean isAnalysisAlgorithm)
            throws ClassNotFoundException, InstantiationException, IllegalAccessException, IOException {

        URL url1 = new URL("file:" + FileUpload.getBaseABSPath()+ File.separator + algorithmRealPath);
        URLClassLoader myClassLoader1 = new URLClassLoader(new URL[]{url1},
                Thread.currentThread().getContextClassLoader());
        Class myClass1 = myClassLoader1.loadClass(PRETREATMENTALGORITHMIMPL);
        try {
            String str = null;
            if (isAnalysisAlgorithm) {
                AnalysisAlgorithm analysisAlgorithm = (AnalysisAlgorithm) myClass1.newInstance();
                str = analysisAlgorithm.execute(JSON.toJSONString(spectrumfile.getPoints()), JSON.toJSONString(spectrumfile.getPoints())); // 标准光谱
            } else {
                PretreatmentAlgorithm pretreatmentAlgorithmImpl = (PretreatmentAlgorithm) myClass1.newInstance();
                str = pretreatmentAlgorithmImpl.execute(JSON.toJSONString(spectrumfile.getPoints()));
            }
            return JSON.parseArray(str);
        } catch (PretreatmentAlgorithmException e) {
            e.printStackTrace();
            logger.error("算法调用失败 : " + e.getMessage());
            return null;
        }
    }
}
